/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.messaging;

import entity.MessageEntity;
import entity.StakeholderEntity;
import entity.OwnerEntity;
import entity.InboxEntity;
import exception.ExistException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import javax.servlet.http.HttpSession;
import org.primefaces.model.MenuModel;
import session.stateless.MessageSessionBean;
import session.stateless.StaffAccountSessionBean;
import session.stateless.StakeholderSessionBeanStateless;
import session.stateless.SystemMessagesBean;
import util.entityhelper.StaffAccountState;
import util.entityhelper.StakeholderAccountState;
import util.generator.StaffMenuGenerator;
import util.localization.WebLocalization;

/**
 *
 * @author KohLi
 */
@ManagedBean
@ViewScoped
public class ViewTrashManagedBean {

    @EJB
    private MessageSessionBean messageSessionbean;
    @EJB
    private StakeholderSessionBeanStateless stakeholderSessionBean;
    @EJB
    private StaffAccountSessionBean staffSessionBean;
    @EJB
    private SystemMessagesBean systemMessages;
    private Long stakeholderId;
    private Long staffAccountId;
    private String nextPage;
    private FacesContext ctx = FacesContext.getCurrentInstance();
    private String preferredLocale;
    private WebLocalization localization;
    private MessageEntity message;
    private List<OwnerEntity> receivers;
    private List<StakeholderEntity> stakeholderList;
    private InboxEntity userMessage;
    private StakeholderAccountState stakeholder;
    private OwnerEntity toWho;
    private OwnerEntity fromWho;
    private List<StaffAccountState> staffList;
    private StaffAccountState staff;
    private String statusMessage;
    private List<MessageEntity> messageList;
    private String ownerName;
    private MessageEntity[] selectedMail;
    private MenuModel staffMenuModel;

    /** Creates a new instance of ViewTrashManagedBean */
    public ViewTrashManagedBean() {

        if (ctx.getExternalContext().getSessionMap().containsKey("stakeholderId")) {
            stakeholderId = (Long) ctx.getExternalContext().getSessionMap().get("stakeholderId");
            // put back the session IDs taken
            ctx.getExternalContext().getSessionMap().put("stakeholderId", stakeholderId);
            System.out.println("stakeholderID at ViewInbox: " + stakeholderId);
        } else if (ctx.getExternalContext().getSessionMap().containsKey("staffAccountId")) {
            // get session values
            staffAccountId = (Long) ctx.getExternalContext().getSessionMap().get("staffAccountId");
            // put back session values
            ctx.getExternalContext().getSessionMap().put("staffAccountId", staffAccountId);
            System.out.println("staffId at ViewInbox: " + staffAccountId);
        } else {
            // redirect back to login
        }
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
        messageList = new ArrayList<MessageEntity>();
        message = new MessageEntity();
    }

    public void initView(PhaseEvent event) throws UnsupportedEncodingException, NoSuchAlgorithmException, IOException {
        FacesContext.getCurrentInstance().getExternalContext().getFlash().clear();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);

        if (stakeholderId == null && staffAccountId == null) {

            setNextPage(FacesContext.getCurrentInstance().getExternalContext().encodeActionURL(FacesContext.getCurrentInstance().getApplication().getViewHandler().getActionURL(FacesContext.getCurrentInstance(), "/StakeholderLogin.xhtml")));
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect(getNextPage());
            } catch (IOException ex) {
                Logger.getLogger(ComposeMessageManagedBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {

            if (getStaffAccountId() != null & staff==null) {
                System.out.println("what is staff account Id: " + getStaffAccountId());
                //load all stakeholderList 
                try {
                    setStaff(getStaffSessionBean().getStaffAccountByID(getStaffAccountId()));
                    ownerName = staff.getUsername();

                    /* PRE-SET MENU BASED ON ACCESS RIGHTS */
                    StaffMenuGenerator menuGenerator = new StaffMenuGenerator(getStaffSessionBean().getStaffAccountByID(getStaffAccountId()));
                    setStaffMenuModel(menuGenerator.generateStaffMenu());
                    /* END PRE-SET MENU BASED ON ACCESS RIGHTS */

                } catch (ExistException ex) {
                    System.out.println(ex.getMessage());
                }
                getMessage().setSender(getStaff().getUsername());
                setStakeholderList(getStakeholderSessionBean().getAllStakeholders());

            } else if (getStakeholder() == null && getStakeholderId() != null) {
                try {
                    stakeholder = stakeholderSessionBean.getPortalDetail(stakeholderId);
                    System.out.println("what is the stakeholder name" + stakeholder.getUsername());
                    ownerName = stakeholder.getUsername();
                } catch (ExistException ex) {
                    System.out.println("exception occurs" + ex.getMessage());
                }
            }
            messageList = messageSessionbean.getMyTrash(ownerName);
            //arrange the list;
        }
    }
    
    
    
    public void view_Deleted_Message(MessageEntity selectedMsg) throws IOException {

        FacesContext.getCurrentInstance().getExternalContext().getFlash().clear();
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("outboxSelectedMsg", messageSessionbean.getMessage(selectedMsg.getId()));

        //redirecting to view edit branch page
        FacesContext ctx = FacesContext.getCurrentInstance();
        String nextPage = ctx.getExternalContext().encodeActionURL(ctx.getApplication().getViewHandler().getActionURL(ctx, "/messaging/ViewDeleteMessage.xhtml"));

        FacesContext.getCurrentInstance().getExternalContext().redirect(nextPage);

    }
    
    
    
    

    public void deleteTrash() throws ExistException, IOException {
        setStaff(getStaffSessionBean().getStaffAccountByID(getStaffAccountId()));
        ownerName = staff.getUsername();
        boolean deleted = messageSessionbean.deleteMessageFromTrash(selectedMail, ownerName);
        if (deleted == true) {
            String statusMessage = systemMessages.getSystemMessage("MAILBOX_TRASH_SUCCESS", preferredLocale);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, statusMessage));
            redirectPage();
        } else {
            String statusMessage = systemMessages.getSystemMessage("MAILBOX_TRASH_NOT_SUCCESSFUL", preferredLocale);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, statusMessage));
        }
    }

    public void redirectPage() {
        if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().containsKey("stakeholderId")) {
            FacesContext ctx = FacesContext.getCurrentInstance();
            String nextPage = ctx.getExternalContext().encodeActionURL(ctx.getApplication().getViewHandler().
                    getActionURL(ctx, "/messaging/Myinbox.xhtml"));
            try {
                ctx.getExternalContext().redirect(nextPage);
            } catch (IOException ex) {
            }
        } else {
            FacesContext ctx = FacesContext.getCurrentInstance();
            String nextPage = ctx.getExternalContext().encodeActionURL(ctx.getApplication().getViewHandler().
                    getActionURL(ctx, "/staff/StaffDeleteTrash.xhtml"));
            try {
                ctx.getExternalContext().redirect(nextPage);
            } catch (IOException ex) {
            }
        }
    }

    /**
     * @return the messageSessionbean
     */
    public MessageSessionBean getMessageSessionbean() {
        return messageSessionbean;
    }

    /**
     * @param messageSessionbean the messageSessionbean to set
     */
    public void setMessageSessionbean(MessageSessionBean messageSessionbean) {
        this.messageSessionbean = messageSessionbean;
    }

    /**
     * @return the stakeholderSessionBean
     */
    public StakeholderSessionBeanStateless getStakeholderSessionBean() {
        return stakeholderSessionBean;
    }

    /**
     * @param stakeholderSessionBean the stakeholderSessionBean to set
     */
    public void setStakeholderSessionBean(StakeholderSessionBeanStateless stakeholderSessionBean) {
        this.stakeholderSessionBean = stakeholderSessionBean;
    }

    /**
     * @return the staffSessionBean
     */
    public StaffAccountSessionBean getStaffSessionBean() {
        return staffSessionBean;
    }

    /**
     * @param staffSessionBean the staffSessionBean to set
     */
    public void setStaffSessionBean(StaffAccountSessionBean staffSessionBean) {
        this.staffSessionBean = staffSessionBean;
    }

    /**
     * @return the systemMessages
     */
    public SystemMessagesBean getSystemMessages() {
        return systemMessages;
    }

    /**
     * @param systemMessages the systemMessages to set
     */
    public void setSystemMessages(SystemMessagesBean systemMessages) {
        this.systemMessages = systemMessages;
    }

    /**
     * @return the stakeholderId
     */
    public Long getStakeholderId() {
        return stakeholderId;
    }

    /**
     * @param stakeholderId the stakeholderId to set
     */
    public void setStakeholderId(Long stakeholderId) {
        this.stakeholderId = stakeholderId;
    }

    /**
     * @return the staffAccountId
     */
    public Long getStaffAccountId() {
        return staffAccountId;
    }

    /**
     * @param staffAccountId the staffAccountId to set
     */
    public void setStaffAccountId(Long staffAccountId) {
        this.staffAccountId = staffAccountId;
    }

    /**
     * @return the nextPage
     */
    public String getNextPage() {
        return nextPage;
    }

    /**
     * @param nextPage the nextPage to set
     */
    public void setNextPage(String nextPage) {
        this.nextPage = nextPage;
    }

    /**
     * @return the ctx
     */
    public FacesContext getCtx() {
        return ctx;
    }

    /**
     * @param ctx the ctx to set
     */
    public void setCtx(FacesContext ctx) {
        this.ctx = ctx;
    }

    /**
     * @return the preferredLocale
     */
    public String getPreferredLocale() {
        return preferredLocale;
    }

    /**
     * @param preferredLocale the preferredLocale to set
     */
    public void setPreferredLocale(String preferredLocale) {
        this.preferredLocale = preferredLocale;
    }

    /**
     * @return the localization
     */
    public WebLocalization getLocalization() {
        return localization;
    }

    /**
     * @param localization the localization to set
     */
    public void setLocalization(WebLocalization localization) {
        this.localization = localization;
    }

    /**
     * @return the message
     */
    public MessageEntity getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(MessageEntity message) {
        this.message = message;
    }

    /**
     * @return the receivers
     */
    public List<OwnerEntity> getReceivers() {
        return receivers;
    }

    /**
     * @param receivers the receivers to set
     */
    public void setReceivers(List<OwnerEntity> receivers) {
        this.receivers = receivers;
    }

    /**
     * @return the stakeholderList
     */
    public List<StakeholderEntity> getStakeholderList() {
        return stakeholderList;
    }

    /**
     * @param stakeholderList the stakeholderList to set
     */
    public void setStakeholderList(List<StakeholderEntity> stakeholderList) {
        this.stakeholderList = stakeholderList;
    }

    /**
     * @return the userMessage
     */
    public InboxEntity getUserMessage() {
        return userMessage;
    }

    /**
     * @param userMessage the userMessage to set
     */
    public void setUserMessage(InboxEntity userMessage) {
        this.userMessage = userMessage;
    }

    /**
     * @return the stakeholder
     */
    public StakeholderAccountState getStakeholder() {
        return stakeholder;
    }

    /**
     * @param stakeholder the stakeholder to set
     */
    public void setStakeholder(StakeholderAccountState stakeholder) {
        this.stakeholder = stakeholder;
    }

    /**
     * @return the toWho
     */
    public OwnerEntity getToWho() {
        return toWho;
    }

    /**
     * @param toWho the toWho to set
     */
    public void setToWho(OwnerEntity toWho) {
        this.toWho = toWho;
    }

    /**
     * @return the fromWho
     */
    public OwnerEntity getFromWho() {
        return fromWho;
    }

    /**
     * @param fromWho the fromWho to set
     */
    public void setFromWho(OwnerEntity fromWho) {
        this.fromWho = fromWho;
    }

    /**
     * @return the staffList
     */
    public List<StaffAccountState> getStaffList() {
        return staffList;
    }

    /**
     * @param staffList the staffList to set
     */
    public void setStaffList(List<StaffAccountState> staffList) {
        this.staffList = staffList;
    }

    /**
     * @return the staff
     */
    public StaffAccountState getStaff() {
        return staff;
    }

    /**
     * @param staff the staff to set
     */
    public void setStaff(StaffAccountState staff) {
        this.staff = staff;
    }

    /**
     * @return the statusMessage
     */
    public String getStatusMessage() {
        return statusMessage;
    }

    /**
     * @param statusMessage the statusMessage to set
     */
    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    /**
     * @return the messageList
     */
    public List<MessageEntity> getMessageList() {
        return messageList;
    }

    /**
     * @param messageList the messageList to set
     */
    public void setMessageList(List<MessageEntity> messageList) {
        this.messageList = messageList;
    }

    /**
     * @return the ownerName
     */
    public String getOwnerName() {
        return ownerName;
    }

    /**
     * @param ownerName the ownerName to set
     */
    public void setOwnerName(String ownerName) {
        this.ownerName = ownerName;
    }

    public MessageEntity[] getSelectedMail() {
        return selectedMail;
    }

    public void setSelectedMail(MessageEntity[] selectedMail) {
        this.selectedMail = selectedMail;
    }

    public MenuModel getStaffMenuModel() {
        return staffMenuModel;
    }

    public void setStaffMenuModel(MenuModel staffMenuModel) {
        this.staffMenuModel = staffMenuModel;
    }
}
